package com.asggo.g21.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.asggo.g21.constant.GsConstants;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * Created by IntelliJ IDEA.
 *
 * @author eric 2023/12/15 16:22
 */
@Slf4j
public class WebSocketInterceptor implements HandshakeInterceptor {

  /**
   * 握手之前触发 (return true 才会握手成功 )
   *
   * @param request    ServerHttpRequest
   * @param response   ServerHttpResponse
   * @param wsHandler  WebSocketHandler
   * @param attributes Map<String, Object>
   * @return 握手成功(true)/失败(false)
   * @throws Exception Exception
   */
  @Override
  public boolean beforeHandshake(@NonNull ServerHttpRequest request,
      @NonNull ServerHttpResponse response,
      @NonNull WebSocketHandler wsHandler, @NonNull Map<String, Object> attributes)
      throws Exception {
    log.info("---- 握手之前触发 " + StpUtil.getTokenValue());

    // 未登录情况下拒绝握手
    if (!StpUtil.isLogin()) {
      log.info("---- 未授权客户端，连接失败");
      return false;
    }

    // 标记 userId，握手成功
    attributes.put(GsConstants.USER_ID, StpUtil.getLoginIdAsLong());

    return true;
  }

  /**
   * 握手之后触发
   *
   * @param request   ServerHttpRequest
   * @param response  ServerHttpResponse
   * @param wsHandler WebSocketHandler
   * @param exception Exception
   */
  @Override
  public void afterHandshake(@NonNull ServerHttpRequest request,
      @NonNull ServerHttpResponse response,
      @NonNull WebSocketHandler wsHandler, Exception exception) {
    // 握手之后要做的事情
    log.info("握手之后....");
  }
}
